/*
Copyright (c) [2019年5月1日] [吴超]
[MBT_studio] is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:
		 http://license.coscl.org.cn/MulanPSL2
THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
*/
#include "stdafx.h"

#include "curve.h"
#include "core/shader_curve.h"
#include "core/shader_built_in_functions.h"

#include "core/属性.h"
#include "core/设备内存缓存.h"

#include "an_曲线.h"

static std::set<S_Props*> g属性动画曲线关键帧;



float32 f_graph_钳制曲线采样(float32 采样位置, const S_曲线& curve, const vec2 钳制) {
	if(curve.count < 2) return 0;

	auto 点 = f_curve_cal_pre(((S_CurvePoint*)curve.point)[0], ((S_CurvePoint*)curve.point)[1]);
	S_CurvePoint* 前一个曲线点 = &点;

	采样位置 = clamp(采样位置, 0, 1);

	for (uint32 i = 0; i < curve.count; ++i) {
		S_CurvePoint* 曲线点 = &((S_CurvePoint*)curve.point)[i];

		if (采样位置 < 曲线点->value.x) {
			float32 步数 = 采样位置 - 前一个曲线点->value.x;
			float32 间隔 = (曲线点->value.x - 前一个曲线点->value.x);
			步数 = 步数 / (间隔+0.00001);
			
			vec2 value = f_curve_cal_point(*前一个曲线点, *曲线点, 步数);
			return clamp(value.y, 0, 1);
		}

		前一个曲线点 = 曲线点;
	}

	vec2 value = f_curve_cal_point(*前一个曲线点, f_curve_cal_next(*前一个曲线点), 采样位置);
	return clamp(value.y, 0, 1);
}

void f_prop_采样曲线拷贝到GPU(S_Props& 采样曲线) {
	auto* curve = f_prop_2DCurve(采样曲线);

	if (采样曲线.m_GPU缓存[0].m_Buf) {
		f_buf_gresize(采样曲线.m_GPU缓存[0], curve->count);

		if (curve->count) {
			for (uint32 i = 0; i < curve->count; ++i) {
				f_buf_曲线段_at(采样曲线.m_GPU缓存[0], i) = curve->point[i];
			}
			f_buf_uVec2_at(采样曲线.m_GPU缓存[1]) = { uint32(采样曲线.m_GPU缓存[0].m_Mem.m_偏移), 采样曲线.m_GPU缓存[0].m_Mem.m_大小 };
		}
	}
}






void f_an_添加属性关键帧(S_Props& 采样曲线) {
	g属性动画曲线关键帧.insert(&采样曲线);

	S_曲线* curve = f_an_创建曲线A();
}

void f_an_移除属性关键帧(S_Props& 采样曲线) {
	g属性动画曲线关键帧.erase(&采样曲线);

	f_an_销毁曲线A((S_曲线*)采样曲线.m_UI->m_关键帧);
}

void f_an_更新属性关键帧() {
	for (auto& e : g属性动画曲线关键帧) {
		switch (e->m_Type) {
			case E_值类型::e_Type_I8: {
				break;
			}
			case E_值类型::e_Type_I32: {
				break;
			}
			case E_值类型::e_Type_UI32: {
				break;
			}
			case E_值类型::e_Type_F32: {
				break;
			}
		}
	}
}





void f_prop_插入关键帧(S_Props& prop, int32 time, float32 value, uint32 id) {
	int32 重叠索引 = f_an_查找重叠帧((S_曲线*)prop.m_UI->m_关键帧, time);

	if (重叠索引 < 0) {
		f_an_添加曲线点((S_曲线*)prop.m_UI->m_关键帧, {float32(time), value}, {}, {}, id, {128,128,128,255});
	}
	else {
		((S_曲线*)prop.m_UI->m_关键帧)->point[重叠索引].value = { float32(time), value };
	}
}

void f_prop_删除关键帧(S_Props& prop, int32 time) {
	//int32 重叠索引 = f_an_查找重叠帧((S_曲线*)prop.m_UI->m_关键帧, time);

	f_an_删除曲线点((S_曲线*)prop.m_UI->m_关键帧, time);
	
}




